﻿using System.Collections.Specialized;

namespace Altairis.IisNetDiag {
    internal static class ExtensionMethods {

        private const string VALID_HOST_PATTERN = @"^([a-zA-Z0-9]+\.?)+$"; // Matches IPv4 address or DNS host name

        public static int GetValue(this NameValueCollection c, string key, int defaultValue, int minValue, int maxValue) {
            var s = c[key];
            int r;
            if (string.IsNullOrEmpty(s) || !int.TryParse(s, out r)) return defaultValue;
            if (r < minValue || r > maxValue) return defaultValue;
            return r;
        }

        public static string GetValue(this NameValueCollection c, string key, string defaultValue) {
            var s = c[key];
            if (string.IsNullOrEmpty(s)) return defaultValue;
            return s;
        }

        public static bool GetValue(this NameValueCollection c, string key, bool defaultValue) {
            var s = c[key];
            bool r;
            if (string.IsNullOrEmpty(s) || !bool.TryParse(s, out r)) return defaultValue;
            return r;
        }

        public static bool IsValidHost(this string hostName) {
            if (string.IsNullOrEmpty(hostName)) return false;
            return System.Text.RegularExpressions.Regex.IsMatch(hostName, VALID_HOST_PATTERN);
        }

    }
}